package initconf

import (
	"errors"
	viewmodel "go_stu_gin/view_model"
	"os"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/rifflock/lfshook"
	"github.com/sirupsen/logrus"
)

func InitLog(config *viewmodel.InitConfig) (*logrus.Logger, error) {
	logConfig := config.Log
	fileName := logConfig.Path
	// 写入文件
	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		return nil, errors.New("打开/写入文件失败." + err.Error())
	}
	// 实例化 设置日志为json格式
	logger := logrus.New()
	logger.SetFormatter(&logrus.JSONFormatter{TimestampFormat: "2006-01-02 15:04:05"})
	// 日志级别
	if logConfig.Level == "info" {
		logger.SetLevel(logrus.InfoLevel)
	} else if logConfig.Level == "error" {
		logger.SetLevel(logrus.ErrorLevel)
	} else if logConfig.Level == "warn" {
		logger.SetLevel(logrus.WarnLevel)
	}

	// 设置输出
	logger.Out = file
	// 设置 rotatelogs,实现文件分割
	logWriter, err := rotatelogs.New(
		// 分割后的文件名称
		fileName+".%Y%m%d.log",
		// 生成软链，指向最新日志文件
		rotatelogs.WithLinkName(fileName),
		// 最大保存时间和日志切割时间只能设置一个
		// 设置最大保存时间
		rotatelogs.WithMaxAge(time.Duration(logConfig.MaxAge)*24*time.Hour), //以hour为单位的整数
		// 设置日志切割时间间隔(1天)
		rotatelogs.WithRotationTime(24*time.Hour),
	)
	if err != nil {
		return nil, errors.New("配置日志分割." + err.Error())
	}
	// hook机制的设置
	writerMap := lfshook.WriterMap{
		logrus.InfoLevel:  logWriter,
		logrus.FatalLevel: logWriter,
		logrus.DebugLevel: logWriter,
		logrus.WarnLevel:  logWriter,
		logrus.ErrorLevel: logWriter,
		logrus.PanicLevel: logWriter,
	}
	//给logrus添加hook
	logger.AddHook(lfshook.NewHook(writerMap, &logrus.JSONFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	}))
	return logger, nil
}
